package weaver.interfaces.shds.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.shds.util.HttpUtils;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.HashMap;
import java.util.Map;

/**
 * @Title
 * @Author wangchaofa
 * @CreateDate 2023/10/30
 * @Version 1.0
 * @Description
 */
public class SynBeAwayOnBusinessAction extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        try {
            String tablename = requestInfo.getRequestManager().getBillTableName();
            String requestid = requestInfo.getRequestid();
            String detailtable = tablename+"_dt1";

            writeLog("============ SynBeAwayOnBusinessAction requestid ===============   " + requestid);

            String appid = getPropValue("shds_travel_erp","appid");
            String appsecret = getPropValue("shds_travel_erp","appsecret");
            String tenantid = getPropValue("shds_travel_erp","tenantid");
            String accountid = getPropValue("shds_travel_erp","accountid");
            String language = getPropValue("shds_travel_erp","language");
            String app_token_url = getPropValue("shds_travel_erp","app_token_url");
            String access_token_url = getPropValue("shds_travel_erp","access_token_url");
            String trip_req_save_url = getPropValue("shds_travel_erp","trip_req_save_url");
            String trip_req_submit_url = getPropValue("shds_travel_erp","trip_req_submit_url");
            String trip_req_audit_url = getPropValue("shds_travel_erp","trip_req_audit_url");

            Map<String,String> headers = new HashMap<>();
            String encode = "utf-8";
            String apptoken = "";
            String accesstoken = "";

            JSONObject json_apptoken = new JSONObject();
            JSONObject json_accesstoken = new JSONObject();

            json_apptoken.put("appId",appid);
            json_apptoken.put("appSecret",appsecret);
            json_apptoken.put("tenantid",tenantid);
            json_apptoken.put("accountId",accountid);
            json_apptoken.put("language",language);

            writeLog("===============  SynBeAwayOnBusinessAction app_token_url ================ "+app_token_url);
            writeLog("===============  SynBeAwayOnBusinessAction access_token_url ================ "+access_token_url);
            writeLog("===============  SynBeAwayOnBusinessAction trip_req_save_url ================ "+trip_req_save_url);
            writeLog("===============  SynBeAwayOnBusinessAction trip_req_submit_url ================ "+trip_req_submit_url);
            writeLog("===============  SynBeAwayOnBusinessAction trip_req_audit_url ================ "+trip_req_audit_url);

            writeLog("===============  SynBeAwayOnBusinessAction json_apptoken ================ "+json_apptoken.toString());

            Map<String,Object> apptokenMap = HttpUtils.getAppToken(app_token_url,headers,json_apptoken.toString(),encode);
            if(apptokenMap.size() > 0){
                apptoken = (String) apptokenMap.get("app_token");
            }
            writeLog("============ SynBeAwayOnBusinessAction apptoken ===============   " + apptoken);

            json_accesstoken.put("apptoken",apptoken);
            json_accesstoken.put("tenantid",tenantid);
            json_accesstoken.put("accountId",accountid);

            RecordSet rs = new RecordSet();
            RecordSet rs1 = new RecordSet();

            JSONObject json_main = new JSONObject();
            JSONObject json_main1 = new JSONObject();

            JSONObject jsonn = new JSONObject();
            JSONObject jsonn1 = new JSONObject();

            String dataSql = " select a.*,b.requestmark from "+tablename+" a,workflow_requestbase b where a.requestid=b.requestid and a.requestid="+requestid;
            rs.execute(dataSql);

            while(rs.next()) {
                String requestmark = Util.null2String(rs.getString("requestmark"));
                jsonn.put("billno",requestmark);
                jsonn.put("shcq_shrid",requestid);
                //主键id
                String mainid = Util.null2String(rs.getString("id"));
                //姓名id
                String resourceId = Util.null2String(rs.getString("resourceId"));
                //员工编码
                String workcode = new ResourceComInfo().getWorkcode(resourceId);

                jsonn.put("applier_number",workcode);

                String email = new ResourceComInfo().getEmail(resourceId);
                json_accesstoken.put("user",email);
                json_accesstoken.put("usertype","Email");

                //部门id
                String departmentId = Util.null2String(rs.getString("departmentId"));
                //部门编码
                String deptcode = new DepartmentComInfo().getDepartmentCode(departmentId);

                jsonn.put("org_number",deptcode);

                jsonn.put("costdept_number",deptcode);

                //分部id
                String subcomid = new DepartmentComInfo().getSubcompanyid1(departmentId);
                //分部编码
                String comcode = new SubCompanyComInfo().getSubCompanyCode(subcomid);

                jsonn.put("company_number",comcode);

                jsonn.put("costcompany_number",comcode);

                //开始日期
                String fromDate = Util.null2String(rs.getString("fromDate"));
                //开始时间
                String fromTime = Util.null2String(rs.getString("fromTime"));
                //结束日期
                String toDate = Util.null2String(rs.getString("toDate"));
                //结束时间
                String toTime = Util.null2String(rs.getString("toTime"));
                //事由说明
                String bz = Util.null2String(rs.getString("bz"));
                if(bz != null && !"".equals(bz)) {
                    bz = bz.trim();
                    bz = bz.replaceAll("&nbsp;", " ");
                }
                jsonn.put("description",bz);
                //出差类型
                String cclxid = Util.null2String(rs.getString("cclx"));
                String cclxName = getCclxname("2");
                String cclx = getCclxCode(cclxName);

                jsonn.put("triptype_number",cclx);

                //出差目的
                String ccmdid = Util.null2String(rs.getString("ccmd"));
                String ccmdName = getCcmdname(ccmdid);
                String ccmd = getCcmdCode(ccmdName);

                jsonn.put("shcq_ccxm_number",ccmd);

                // 时长（天）
                double duration = Util.getDoubleValue(rs.getString("duration"),0);
                int roundedNum = (int) Math.ceil(duration/8);
                jsonn.put("plandays",roundedNum);

                JSONArray jsonArray = new JSONArray();
                rs1.executeQuery("select * from "+ detailtable +" where mainid=?",mainid);
                while(rs1.next()){
                    JSONObject jsonObject = new JSONObject();
                    //开始日期
                    String ksrq = Util.null2String(rs1.getString("ksrq"));
                    //结束日期
                    String jsrq = Util.null2String(rs1.getString("jsrq"));
                    //出发地
                    String cfdid = Util.null2String(rs1.getString("cfd"));
                    String cfdName = getCityname(cfdid);
                    String cfd = getCityCode(cfdName);

                    //目的地
                    String mddid = Util.null2String(rs1.getString("mdd"));
                    String mddName = getCityname(mddid);
                    String mdd = getCityCode(mddName);

                    //途径地
                    String tjdid = Util.null2String(rs1.getString("tjd"));
                    String tjdName = getCityname(tjdid);
                    String tjd = getCityCode(tjdName);

                    jsonObject.put("from_number",cfd);
                    jsonObject.put("to_number",mdd);
                    jsonObject.put("startdate",fromDate+" "+fromTime+":00");
                    jsonObject.put("enddate",toDate+" "+toTime+":00");
                    jsonObject.put("entrycostdept_number",deptcode);
                    jsonObject.put("entrycostcompany_number",comcode);

                    jsonArray.add(jsonObject);
                }
                jsonn.put("tripentry",jsonArray);
            }
            json_main.put("data",jsonn);
            writeLog("============ SynBeAwayOnBusinessAction  JSON PARAM ===============   " + json_main);

            Map<String,Object> accesstokenMap = HttpUtils.getAccessToken(access_token_url,headers,json_accesstoken.toString(),encode);
            if(accesstokenMap.size() > 0){
                accesstoken = (String) accesstokenMap.get("access_token");
            }
            writeLog("============ SynBeAwayOnBusinessAction  accesstoken ===============   " + accesstoken);

            headers.put("accesstoken", accesstoken);

            //保存
            String pkId = HttpUtils.pushInfoSave(trip_req_save_url,headers,json_main.toString(),encode);
            writeLog("============ SynBeAwayOnBusinessAction  PUSH MESSAGE  SAVE  RESULT ===============   " + pkId);
            if(pkId!=null && !"".equals(pkId)){
                jsonn1.put("id",pkId);
                json_main1.put("data",jsonn1);
                writeLog("============ SynBeAwayOnBusinessAction pushInfoSubmit JSON PARAM ===============   " + json_main1);
                boolean bool1 = HttpUtils.pushInfoSubmit(trip_req_submit_url,headers,json_main1.toString(),encode);
                writeLog("============ SynBeAwayOnBusinessAction pushInfoSubmit RESULT ===============   " + bool1);
                if(bool1){
                    boolean bool2 = HttpUtils.pushInfoAudit(trip_req_audit_url,headers,json_main1.toString(),encode);
                    writeLog("============ SynBeAwayOnBusinessAction pushInfoAudit RESULT ===============   " + bool2);
                    if(bool2){
                        return Action.SUCCESS;
                    }else{
                        requestInfo.getRequestManager().setMessagecontent("公出信息推送至ERP系统审批时发生异常，请联系管理员！");
                        return Action.FAILURE_AND_CONTINUE;
                    }
                }else{
                    requestInfo.getRequestManager().setMessagecontent("公出信息推送至ERP系统提交时发生异常，请联系管理员！");
                    return Action.FAILURE_AND_CONTINUE;
                }
            }else{
                requestInfo.getRequestManager().setMessagecontent("公出信息推送至ERP系统保存时发生异常，请联系管理员！");
                return Action.FAILURE_AND_CONTINUE;
            }
        }catch (Exception e){
            writeLog(e);
            e.printStackTrace();
            requestInfo.getRequestManager().setMessagecontent("公出信息推送至ERP系统发生异常，请联系管理员！");
            return Action.FAILURE_AND_CONTINUE;
        }
    }

    public static String getDeptCode(String deptid){
        String code = "";
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from hrmdepartment where id=?",deptid);
        while(rs.next()){
            code = Util.null2String(rs.getString("departmentcode"));
        }
        return code;
    }

    public static String getSubComCode(String deptid){
        String code = "";
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from hrmsubcompany where id=?",deptid);
        while(rs.next()){
            code = Util.null2String(rs.getString("sumcompanycode"));
        }
        return code;
    }

    /**
     * 获取出差目的 名称
     * @param id
     * @return
     */
    public static String getCcmdname(String id){
        String name = "";
        RecordSet rs = new RecordSet();
        String ccmd_fieldid = rs.getPropValue("shds_travel_erp","ccmd_fieldid");
        rs.executeQuery("select * from workflow_selectitem where fieldid=? and cancel=0 and selectvalue=?",ccmd_fieldid,id);
        while(rs.next()) {
            name = Util.null2String(rs.getString("selectname"));
        }
        return name;
    }

    /**
     * 获取出差类型 名称
     * @param id
     * @return
     */
    public static String getCclxname(String id){
        String name = "";
        RecordSet rs = new RecordSet();
        String cclx_fieldid = rs.getPropValue("shds_travel_erp","gc_cclx_fieldid");
        rs.executeQuery("select * from workflow_selectitem where fieldid=?  and selectvalue=?",cclx_fieldid,id);
        while(rs.next()) {
            name = Util.null2String(rs.getString("selectname"));
        }
        return name;
    }

    /**
     * 获取城市 名称
     * @param id
     * @return
     */
    public static String getCityname(String id){
        String name = "";
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from hrmcity where  canceled=0 or canceled is null and id=?",id);
        while(rs.next()) {
            String cityname = Util.null2String(rs.getString("cityname"));
            if(cityname.length() > 10){
                name = cityname.substring(6,8);
            }else{
                name = cityname;
            }
        }
        return name;
    }

    /**
     * 根据名称查询对应的编码
     * @param name
     * @return
     */
    public static String getCityCode(String name){
        String code = "";
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from uf_qydyb where xzjc like '%市%' and mc=?",name);
        while(rs.next()) {
            code = Util.null2String(rs.getString("bm"));
        }
        return code;
    }

    public static String getCclxCode(String name){
        String code = "";
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from uf_cclxb where  cclx=?",name);
        while(rs.next()) {
            code = Util.null2String(rs.getString("code"));
        }
        return code;
    }

    public static String getCcmdCode(String name){
        String code = "";
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from uf_ccmdb where  ccmdmc=?",name);
        while(rs.next()) {
            code = Util.null2String(rs.getString("ccmdbm"));
        }
        return code;
    }

}
